import {defineComponent, watch, shallowReactive, ref} from 'vue'

// 声明类型
const PropsType = {
  cdata: {
    type: Object,
    require: true
  }
} as const

// 定义主体
export default defineComponent({
  props: PropsType,
  setup(props) {
    // 定义固定配置项
    const lineStyle = {
      normal: {
        width: 1,
        opacity: 0.5
      }
    };
    const chartRef = ref(null)
    // 配置项
    let options = {}

    watch(
      () => props.cdata,
      (val: any) => {
        options = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              crossStyle: {
                color: '#999'
              }
            },
            // 自定义tooltip内容格式
            formatter: function(params) {
              let result = `<div style="font-weight: bold;">${params[0].name}</div>`;

              // 处理充放电状态数据
              const chargeData = params.find(p => p.seriesName === '充放电状态');
              if (chargeData) {
                const value = chargeData.value;
                const status = value >= 0 ? '充电' : '放电';
                result += `<div>${status}：${Math.abs(value)}kWh</div>`;
              }

              // 处理电池电量数据
              const energyData = params.find(p => p.seriesName === '电池电量');
              if (energyData) {
                result += `<div>当前电量：${energyData.value}%</div>`;
              }

              return result;
            }
          },
          legend: {
            data: ['充放电状态', '电池电量']
          },
          xAxis: {
            type: 'category',
            data: val.hours
          },
          yAxis: [
            {
              type: 'value',
              name: '充放电电量 (kWh)',
              axisLabel: {
                formatter: '{value} kWh'
              }
            },
            {
              type: 'value',
              name: '电池电量 (%)',
              max: 100,
              axisLabel: {
                formatter: '{value} %'
              },
              position: 'right'
            }
          ],
          series: [
            {
              name:'充放电状态',
              data:val.chargeStatus,
              type:'bar',
              yAxisIndex: 0,
            },
            {
              name:'电池电量',
              data: val.batteryEnergy,
              type: 'line',
              yAxisIndex: 1,
            }
          ]
        };
        if (chartRef.value) {
          // 通过初始化参数打入数据
          chartRef.value.initChart(options)
        }
      },
      {
        immediate: true,
        deep: true
      }
    )

    return () => {
      const height = "400px"
      const width = "450px"

      return <div>
        <echart ref={chartRef} options={options} height={height} width={width} />
      </div>
    }
  }
})

